// 周期传输统计组件 
import React, { useState, useEffect } from 'react';
import { Table, Spin } from 'antd';
import pointsService from '../../../../services/points';

const WeeklyStats = ({ networkId, onError }) => {
  const [accumulations, setAccumulations] = useState([]);
  const [loading, setLoading] = useState(true);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 20,
    total: 0
  });

  // 获取周期传输统计数据
  const fetchWeeklyStats = async (page = 1, size = 20) => {
    try {
      setLoading(true);
      const response = await pointsService.getNetworkWeeklyStats(networkId, { page, size });
      if (response.data.code === 200) {
        setAccumulations(response.data.data.accumulations || []);
        setPagination({
          current: response.data.data.pageNum,
          pageSize: response.data.data.pageSize,
          total: response.data.data.total
        });
      } else {
        onError('获取周期统计失败');
      }
    } catch (error) {
      onError('获取周期统计失败');
    } finally {
      setLoading(false);
    }
  };

  // 格式化文件大小
  const formatFileSize = (bytes) => {
    if (bytes === 0) return '0 B';
    const k = 1024;
    const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
  };

  // 表格列定义
  const columns = [
    {
      title: '用户ID',
      dataIndex: 'userId',
      key: 'userId'
    },
    {
      title: '周期上传量',
      dataIndex: 'periodUploaded',
      key: 'periodUploaded',
      render: (bytes) => formatFileSize(bytes),
      sorter: true
    },
    {
      title: '周期下载量',
      dataIndex: 'periodDownloaded',
      key: 'periodDownloaded',
      render: (bytes) => formatFileSize(bytes),
      sorter: true
    },
    {
      title: '结算开始时间',
      dataIndex: 'settlementStart',
      key: 'settlementStart',
      render: (date) => new Date(date).toLocaleString('zh-CN')
    },
    {
      title: '下次结算时间',
      dataIndex: 'nextSettlement',
      key: 'nextSettlement',
      render: (date) => new Date(date).toLocaleString('zh-CN')
    }
  ];

  // 处理表格变化
  const handleTableChange = (paginationInfo) => {
    fetchWeeklyStats(paginationInfo.current, paginationInfo.pageSize);
  };

  useEffect(() => {
    if (networkId) {
      fetchWeeklyStats();
    }
  }, [networkId]);

  return (
    <div>
      <Table
        columns={columns}
        dataSource={accumulations}
        rowKey="accumulationId"
        loading={loading}
        pagination={{
          ...pagination,
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total, range) => 
            `第 ${range[0]}-${range[1]} 条，共 ${total} 条`
        }}
        onChange={handleTableChange}
      />
    </div>
  );
};

export default WeeklyStats; 